//
// Created by yyl on 2021/7/27.
//

#include "ThreadJvmUtils.h"

void testThread() {
    auto javaVm = getVM();
    JNIEnv *env;
    int envState = javaVm->GetEnv((void **) &env, JNI_VERSION_1_6);
    if (envState == JNI_EDETACHED) {//从虚拟机分离的线程  (子线程)JVM线程
        LOGI("notifyState JVM线程切换至JNI线程");
        auto result = javaVm->AttachCurrentThread(&env, NULL);
        if (result == JNI_OK) {

        }
    } else if (envState == JNI_OK) {
        LOGI("notifyState JNI线程回调");
//                env->CallVoidMethod(stateJava.callbackObj, stateJava.notifyState, state,
//                                    actionState, error);
    } else if (envState == JNI_EVERSION) {//版本错误

    }
}

//pthread_key_t，将在线程退出时回调一个“析构函数”，
// 该“析构函数”的参数是由此前通过pthread_setspecific设置得到的。
void detachKeyDestructor(void *arg) {
//    pthread_t thd = pthread_self();
    LOGI("javaAttachThread --->>>解除JVM线程依赖 detachKey");
    auto javaVm = getVM();
    javaVm->DetachCurrentThread();
}

JNIEnv *ThreadJvmUtils::javaAttachThread() {
    auto javaVm = getVM();
    JNIEnv *jenv = NULL;
    int status = javaVm->GetEnv((void **) &jenv, JNI_VERSION_1_6);
    if (status == JNI_EDETACHED) {
        LOGI("javaAttachThread 创建detachKey");
        pthread_key_create(&detachKey, detachKeyDestructor);
        javaVm->AttachCurrentThread(&jenv, NULL);
        pthread_setspecific(detachKey, javaVm);
    }
    return jenv;
}
